#!coding:utf-8
import freebase
import sys
from translatesegment import translate

def performance_row(p): 
	""" str performance """
	res = u'* '+inlink(translate(p['actor']))
	if res == None:
		return ""
	if p['character']:
		res += u" в ролі "+translate(p['character'])
	return res+'\n'

def inlink(s):
	if len(s)>0:
		return u'[['+s+u']]'
	else:
		return ""

def trans_seg_list(l,separator=", "):
	""" Translate list of segments """
	return separator.join(map(lambda x: inlink(translate(x)),l))

def iso8601(d):
	""" From iso8601 to Ukrainian """
	l= d.split('-')
	if len(l)<2:
		return l[0]
	months = {
		"01":u'січня',
		"02":u'лютого',
		"03":u'березня',
		"04":u'квітня',
		"05":u'травня',
		"06":u'червня',
		"07":u'липня',
		"08":u'серпня',
		"09":u'вересня',
		"10":u'жовтня',
		"11":u'листопада',
		"12":u'грудня'
	}

	return l[2]+u' '+months[l[1]]+u' '+l[0]

def iso8601year(d):
	""" get year from iso8601 """
	return d.split('-')[0]

def strmoney(datedmoney):
	if len(datedmoney)<1:
		return ''
	datedmoney = datedmoney[0]
	if datedmoney['currency']=='US$':
		cur = '$'
	val = datedmoney['amount']
	if val>1000000:
		return str(int(val/1000000.0))+u' млн '+cur
	else:
		return str(int(val))+cur

	

def getarticle(name):
	query = [{
		'type':'/film/film',
		'name':name, #Hot Fuzz',
		'id':None,
		'directed_by':[],
		'produced_by':[],
		'starring':[{'actor':None, 'character':None, 'character_note':None}],
		'language':[],
		'genre':[],
		'initial_release_date':None,
		'written_by':[],
		'music':[],
		'cinematography':[],
		'edited_by':[],
		'rating':[],
		'production_companies':[],
		'distributors':[],
		'sequel':None,
		'prequel':None,
		'runtime':[{'runtime':None}],
		'country':[],
		'estimated_budget':[{'amount':None, 'currency':None, 'optional':True}],
		'gross_revenue':[{'amount':None, 'currency':None,'optional':True}],
		'rottentomatoes_id':None,
		'key':[{'namespace':None,'value':None}],
	}]
	res= freebase.mqlread(query)
	if not res:
		print "Fuck!"
		return ""
	res = res[0]
	article = {}
	article['enname'] = res['name']
	article['ukname'] = translate(res['name'])
	article['genre'] = trans_seg_list(res['genre'])
	article['language'] = trans_seg_list(res['language'])
	article['director'] = trans_seg_list(res['directed_by'])
	article['producer'] = trans_seg_list(res['produced_by'])
	article['writer'] = trans_seg_list(res['written_by'])
	article['cast_column'] = trans_seg_list(map(lambda x: x['actor'], res['starring']),"<br /> ")
	article['cast'] = "".join(map(performance_row,res['starring']))
	article['release'] = iso8601(res['initial_release_date'])
	article['year'] = iso8601year(res['initial_release_date'])
	article['composer'] = trans_seg_list(res['music'])
	article['cinematographer'] = trans_seg_list(res['cinematography'])
	article['editor'] = trans_seg_list(res['edited_by'])
	article['rating'] = res['rating'][0]
	article['production_companies'] = trans_seg_list(res['production_companies'])
	article['distributors'] = trans_seg_list(res['distributors'])
	article['sequel'] = translate(res['sequel'])
	article['prequel'] = translate(res['prequel'])
	article['runtime'] = str(int(res['runtime'][0]['runtime']))+u' хв'
	article['country'] = trans_seg_list(res['country'])
	article['budget'] = strmoney(res['estimated_budget'])
	article['grossrevenue'] = strmoney(res['gross_revenue'])
	article['tomatoesid'] = res['rottentomatoes_id']
	akeys = dict(map(lambda x: (x['namespace'],x['value']),res['key']))
	article['imdbid'] = akeys['/authority/imdb/title'][2:]
	if '/source/metacritic/movie' in akeys:
		article['metacriticid'] = akeys['/source/metacritic/movie']
	else:
		article['metacriticid'] = ''
	article['freebaseid'] = res['id']
	return article

print u"""{{Фільм
| українська назва  = %(ukname)s
| оригінальна назва = %(enname)s
| плакат            = <!-- [[Файл:|200px]] -->
| жанр              = %(genre)s
| режисер           = %(director)s 
| продюсер          = %(producer)s
| сценарист         = %(writer)s
| актори            = %(cast_column)s
| композитор        = %(composer)s
| оператор          = %(cinematographer)s
| монтаж            = %(editor)s
| кінокомпанія      = %(production_companies)s
| дистриб’ютор      = %(distributors)s
| тривалість        = %(runtime)s
| кошторис          = %(budget)s 
| касові збори      = %(grossrevenue)s
| країна            = %(country)s
| рік               = %(year)s
| дата виходу       = %(release)s
| рейтинг           = {{fratings|MPAA=%(rating)s}}
| ідентифікатор     = %(imdbid)s
| мова              = %(language)s
| попередній        = %(sequel)s
| наступний         = %(prequel)s
| сайт              = 
}}

'''%(ukname)s''' ({{lang-en|%(enname)s}}) - фільм

== Сюжет ==
{{section-stub}}

== В ролях ==
%(cast)s

== Посилання ==
* Використано матеріали з бази даних [http://www.freebase.com/view%(freebaseid)s Freebase].
* {{Imdb title|%(imdbid)s|%(enname)s}}
* {{rotten-tomatoes|id=%(tomatoesid)s|title=%(enname)s}}
* {{metacritic film|%(metacriticid)s}}

{{film-stub}}

[[en:%(enname)s]]
""" % getarticle("Men at Work")
